package cn.lyh.edu.service.impl;
//接口实现类

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lyh.exception.BadRequestException;
import cn.lyh.edu.domain.EduNews;
import cn.lyh.edu.repository.EduNewsRepository;
import cn.lyh.edu.service.IEduNewsService;
import cn.lyh.edu.service.dto.NewsQueryCriteria;
import cn.lyh.utils.PageUtil;
import cn.lyh.utils.QueryHelp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class EduNewsServiceImpl implements IEduNewsService {

    private final EduNewsRepository eduNewsRepository;

    public EduNewsServiceImpl(EduNewsRepository eduNewsRepository) {
        this.eduNewsRepository = eduNewsRepository;
    }
    /**
     * 获取房间类型列表数据
     * @param queryCriteria
     * @param pageable
     * @return
     */
    @Override
    public Object getList(NewsQueryCriteria queryCriteria, Pageable pageable) {
        Page<EduNews> page= eduNewsRepository.findAll((root, query, criteriaBuilder)->
                QueryHelp.getPredicate(root,queryCriteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page);
    }

    /**
     * 新增房间类型
     * @param eduNews
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addNews(EduNews eduNews) {
        EduNews dbEduNews =  eduNewsRepository.save(eduNews);
        if(dbEduNews.getId()==null||dbEduNews.getId()==0){
            throw new BadRequestException("新增房间类型失败");
        }
    }

    /**
     * 根据ID获取房间类型详情信息
     * @param id
     * @return
     */
    @Override
    public EduNews getById(Long id) {
        return eduNewsRepository.findById(id).orElseGet(EduNews::new);
    }

    /**
     * 更新房间类型信息
     * @param eduNews
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editNews(EduNews eduNews) {
        EduNews dbEduNews =  eduNewsRepository.getReferenceById(eduNews.getId());
        BeanUtil.copyProperties(eduNews,dbEduNews, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        eduNewsRepository.save(dbEduNews);
    }

    /**
     * 删除房间类型信息
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        eduNewsRepository.deleteById(id);}

    /**
     * 获取所有新闻
     * @return
     */
   @Override
    public List<EduNews> getAll() {
        return eduNewsRepository.findAll();
    }

    }

